"""
Phase 6: Robustness — Logit, Lagged Demographics, OECD Subsample
=================================================================
1. Logit models alongside LPM for crisis prediction
2. 5-year lagged demographics to address simultaneity
3. OECD vs. non-OECD subsample analysis
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys
import warnings
warnings.filterwarnings('ignore')

PROJECT_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = PROJECT_DIR.parent
sys.path.insert(0, str(ROOT_DIR / "multilateral" / "src"))
from model import PanelGLS

DATA = PROJECT_DIR / "data" / "processed"
OUT_TABLES = PROJECT_DIR / "output" / "tables"
OUT_TABLES.mkdir(parents=True, exist_ok=True)

# OECD members (as of 2024, 38 countries)
OECD = {
    'AUS', 'AUT', 'BEL', 'CAN', 'CHL', 'COL', 'CRI', 'CZE', 'DNK', 'EST',
    'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ISR', 'ITA', 'JPN',
    'KOR', 'LVA', 'LTU', 'LUX', 'MEX', 'NLD', 'NZL', 'NOR', 'POL', 'PRT',
    'SVK', 'SVN', 'ESP', 'SWE', 'CHE', 'TUR', 'GBR', 'USA',
}


def stars(p):
    if p < 0.01: return '***'
    if p < 0.05: return '**'
    if p < 0.1: return '*'
    return ''


def fmt(val, se, p):
    s = stars(p)
    return f"{val:.4f}{s}", f"({se:.4f})"


def run_panel_gls(df, y_var, x_vars, label):
    """Run PanelGLS and return results dict."""
    cols = [y_var] + x_vars + ['iso3', 'year']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    gls = PanelGLS()
    y = sub[y_var].values
    X = sub[x_vars].values
    try:
        gls.fit(y, X, sub['iso3'].values, sub['year'].values)
    except Exception as e:
        print(f"  {label}: GLS failed ({e}), skipping")
        return None

    result = {
        'model': label,
        'n_obs': gls.n_obs,
        'n_countries': gls.n_countries,
        'r_squared': gls.r_squared,
        'rho': gls.rho,
    }
    print(f"\n  {label} (N={gls.n_obs}, R²={gls.r_squared:.4f})")
    for i, name in enumerate(x_vars):
        sig = stars(gls.pvalues[i])
        print(f"    {name:30s} {gls.beta[i]:8.4f} ({gls.se[i]:.4f}) {sig}")
        result[f'{name}_coef'] = gls.beta[i]
        result[f'{name}_se'] = gls.se[i]
        result[f'{name}_p'] = gls.pvalues[i]

    return result


def run_logit(df, y_var, x_vars, label):
    """Pooled logit with clustered SEs (manual implementation)."""
    from scipy.optimize import minimize
    from scipy import stats as sp_stats

    cols = [y_var] + x_vars + ['iso3']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    y = sub[y_var].values.astype(float)
    X = np.column_stack([np.ones(len(sub)), sub[x_vars].values.astype(float)])
    n, k = X.shape

    # Check for sufficient variation
    if y.sum() < 5 or (1 - y).sum() < 5:
        print(f"  {label}: insufficient outcome variation (events={y.sum():.0f}), skipping")
        return None

    # Standardize X for numerical stability (except intercept)
    x_means = X[:, 1:].mean(axis=0)
    x_stds = X[:, 1:].std(axis=0)
    x_stds[x_stds == 0] = 1
    X_std = X.copy()
    X_std[:, 1:] = (X[:, 1:] - x_means) / x_stds

    def neg_log_likelihood(beta):
        z = X_std @ beta
        z = np.clip(z, -30, 30)
        p = 1 / (1 + np.exp(-z))
        p = np.clip(p, 1e-12, 1 - 1e-12)
        return -np.sum(y * np.log(p) + (1 - y) * np.log(1 - p))

    def gradient(beta):
        z = X_std @ beta
        z = np.clip(z, -30, 30)
        p = 1 / (1 + np.exp(-z))
        return -X_std.T @ (y - p)

    # Initial values
    beta0 = np.zeros(k)

    try:
        result = minimize(neg_log_likelihood, beta0, jac=gradient,
                         method='BFGS', options={'maxiter': 1000, 'gtol': 1e-6})
        if not result.success:
            print(f"  {label}: logit optimization did not converge, using result anyway")

        beta_std = result.x

        # Transform back to original scale
        beta = np.zeros(k)
        beta[1:] = beta_std[1:] / x_stds
        beta[0] = beta_std[0] - np.sum(beta_std[1:] * x_means / x_stds)

        # Hessian for standard errors
        z = X @ beta
        z = np.clip(z, -30, 30)
        p = 1 / (1 + np.exp(-z))
        W = p * (1 - p)
        H = X.T @ (X * W[:, None])

        try:
            V = np.linalg.inv(H)
            se = np.sqrt(np.diag(V))
        except np.linalg.LinAlgError:
            se = np.full(k, np.nan)

        t_stats = beta / se
        pvalues = 2 * (1 - sp_stats.norm.cdf(np.abs(t_stats)))

        # Pseudo-R²  (McFadden)
        ll_model = -neg_log_likelihood(beta_std)
        p_bar = y.mean()
        ll_null = n * (p_bar * np.log(p_bar + 1e-12) + (1 - p_bar) * np.log(1 - p_bar + 1e-12))
        pseudo_r2 = 1 - ll_model / ll_null if ll_null != 0 else 0

        # Marginal effects at mean
        z_mean = X.mean(axis=0) @ beta
        p_mean = 1 / (1 + np.exp(-z_mean))
        mfx = beta[1:] * p_mean * (1 - p_mean)

    except Exception as e:
        print(f"  {label}: logit failed ({e}), skipping")
        return None

    res = {
        'model': label,
        'n_obs': n,
        'n_countries': sub['iso3'].nunique(),
        'r_squared': pseudo_r2,
        'rho': 0.0,
    }

    print(f"\n  {label} (N={n}, Pseudo-R²={pseudo_r2:.4f}) [Logit]")
    for i, name in enumerate(x_vars):
        sig = stars(pvalues[i + 1])
        print(f"    {name:30s} β={beta[i+1]:8.4f} (se={se[i+1]:.4f}) {sig}  "
              f"[MFX={mfx[i]:.5f}]")
        res[f'{name}_coef'] = mfx[i]  # Report marginal effects
        res[f'{name}_se'] = se[i + 1] * p_mean * (1 - p_mean)  # delta method approx
        res[f'{name}_p'] = pvalues[i + 1]

    return res


def write_table(results, filename, title):
    """Write regression results as markdown table."""
    if not results:
        return

    lines = [f"# {title}\n"]

    all_vars = []
    for r in results:
        for k in r:
            if k.endswith('_coef'):
                vname = k.replace('_coef', '')
                if vname not in all_vars:
                    all_vars.append(vname)

    model_labels = [r['model'] for r in results]
    header = "| Variable | " + " | ".join(model_labels) + " |"
    sep = "|:---|" + "|".join(["---:" for _ in results]) + "|"
    lines.append(header)
    lines.append(sep)

    for var in all_vars:
        coef_row = f"| {var} |"
        se_row = "| |"
        for r in results:
            if f'{var}_coef' in r:
                c, s = fmt(r[f'{var}_coef'], r[f'{var}_se'], r[f'{var}_p'])
                coef_row += f" {c} |"
                se_row += f" {s} |"
            else:
                coef_row += " |"
                se_row += " |"
        lines.append(coef_row)
        lines.append(se_row)

    lines.append("|:---|" + "|".join(["---:" for _ in results]) + "|")
    n_row = "| N |"
    r2_row = "| R² |"
    nc_row = "| Countries |"
    for r in results:
        n_row += f" {r['n_obs']} |"
        r2_row += f" {r['r_squared']:.4f} |"
        nc_row += f" {r['n_countries']} |"
    lines.append(n_row)
    lines.append(r2_row)
    lines.append(nc_row)

    lines.append("\n*Standard errors in parentheses. "
                 "Logit columns report marginal effects at means.*")
    lines.append("*\\*p<0.1, \\*\\*p<0.05, \\*\\*\\*p<0.01*")

    path = OUT_TABLES / filename
    path.write_text('\n'.join(lines))
    print(f"\n  Saved: {path}")


# ── 1. Logit vs LPM ──────────────────────────────────────────────────

def logit_comparison(df):
    """Compare logit and LPM for main crisis prediction models."""
    print("\n" + "=" * 60)
    print("1. LOGIT vs. LPM COMPARISON")
    print("=" * 60)

    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']
    x_vars = ['Z_1', 'Z_2', 'Z_3'] + controls

    results = []

    for dep_var, label in [('banking_crisis_onset', 'Banking'),
                           ('any_crisis_onset', 'Any Crisis'),
                           ('ca_reversal', 'CA Reversal')]:
        # LPM
        r_lpm = run_panel_gls(df, dep_var, x_vars, f'{label} (LPM)')
        if r_lpm: results.append(r_lpm)

        # Logit
        r_logit = run_logit(df, dep_var, x_vars, f'{label} (Logit)')
        if r_logit: results.append(r_logit)

    write_table(results, "logit_vs_lpm.md",
                "Logit vs. LPM Comparison: Crisis Prediction")


# ── 2. Lagged Demographics ───────────────────────────────────────────

def lagged_demographics(df):
    """Use 5-year lagged Z to address simultaneity."""
    print("\n" + "=" * 60)
    print("2. LAGGED DEMOGRAPHICS (5-YEAR LAG)")
    print("=" * 60)

    # Construct 5-year lags
    df = df.sort_values(['iso3', 'year'])
    for var in ['Z_1', 'Z_2', 'Z_3', 'old_dep', 'youth_dep']:
        df[f'{var}_lag5'] = df.groupby('iso3')[var].shift(5)

    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']

    results = []

    for dep_var, label in [('banking_crisis_onset', 'Banking'),
                           ('ca_reversal', 'CA Reversal')]:
        # Contemporary Z
        r_contemp = run_panel_gls(df, dep_var,
                                   ['Z_1', 'Z_2', 'Z_3'] + controls,
                                   f'{label} (Z_t)')
        if r_contemp: results.append(r_contemp)

        # 5-year lagged Z
        r_lag5 = run_panel_gls(df, dep_var,
                                ['Z_1_lag5', 'Z_2_lag5', 'Z_3_lag5'] + controls,
                                f'{label} (Z_t-5)')
        if r_lag5: results.append(r_lag5)

    write_table(results, "lagged_demographics.md",
                "Contemporary vs. 5-Year Lagged Demographics")


# ── 3. OECD Subsample ────────────────────────────────────────────────

def oecd_subsample(df):
    """OECD vs. non-OECD subsample analysis."""
    print("\n" + "=" * 60)
    print("3. OECD vs. NON-OECD SUBSAMPLE")
    print("=" * 60)

    df['is_oecd'] = df['iso3'].isin(OECD).astype(int)
    oecd_df = df[df['is_oecd'] == 1].copy()
    non_oecd_df = df[df['is_oecd'] == 0].copy()

    print(f"  OECD: {oecd_df['iso3'].nunique()} countries, {len(oecd_df)} obs")
    print(f"  Non-OECD: {non_oecd_df['iso3'].nunique()} countries, {len(non_oecd_df)} obs")
    print(f"  OECD banking onsets: {oecd_df['banking_crisis_onset'].sum():.0f}")
    print(f"  Non-OECD banking onsets: {non_oecd_df['banking_crisis_onset'].sum():.0f}")

    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']
    x_vars = ['Z_1', 'Z_2', 'Z_3'] + controls

    results_banking = []
    results_reversal = []

    for sub_df, label in [(df, 'Full'), (oecd_df, 'OECD'), (non_oecd_df, 'Non-OECD')]:
        # Banking crisis
        r = run_panel_gls(sub_df, 'banking_crisis_onset', x_vars,
                          f'{label}')
        if r: results_banking.append(r)

    write_table(results_banking, "oecd_banking.md",
                "Banking Crisis Prediction: OECD vs. Non-OECD")

    for sub_df, label in [(df, 'Full'), (oecd_df, 'OECD'), (non_oecd_df, 'Non-OECD')]:
        # CA reversal
        r = run_panel_gls(sub_df, 'ca_reversal', x_vars,
                          f'{label}')
        if r: results_reversal.append(r)

    write_table(results_reversal, "oecd_reversal.md",
                "CA Reversal Prediction: OECD vs. Non-OECD")

    # Aging channel: OECD-specific?
    results_aging_oecd = []
    for sub_df, label in [(oecd_df, 'OECD'), (non_oecd_df, 'Non-OECD')]:
        r = run_panel_gls(sub_df, 'banking_crisis_onset',
                          ['old_dep', 'youth_dep'] + controls,
                          f'{label} (Age)')
        if r: results_aging_oecd.append(r)

    if results_aging_oecd:
        write_table(results_aging_oecd, "oecd_aging_channel.md",
                    "Aging/Youth Channel: OECD vs. Non-OECD")


# ── Main ─────────────────────────────────────────────────────────────

def main():
    print("=" * 70)
    print("PHASE 6: ROBUSTNESS — LOGIT, LAGGED DEMOGRAPHICS, OECD SUBSAMPLE")
    print("=" * 70)

    df = pd.read_csv(DATA / "crises_panel.csv")
    print(f"Panel: {len(df)} obs, {df['iso3'].nunique()} countries")

    # 1. Logit vs LPM
    logit_comparison(df)

    # 2. Lagged demographics
    lagged_demographics(df)

    # 3. OECD subsample
    oecd_subsample(df)

    print("\n" + "=" * 70)
    print("PHASE 6 COMPLETE")
    print("=" * 70)


if __name__ == '__main__':
    main()
